package it.yuzuojian.com.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import it.yuzuojian.com.javaBean.Article;
import it.yuzuojian.com.javaBean.ArticleTags;
import it.yuzuojian.com.javaBean.SearchJavaBean;
import it.yuzuojian.com.javaBean.Tags;
import it.yuzuojian.com.service.ArticleService;
import it.yuzuojian.com.service.ArticleTagsService;
import it.yuzuojian.com.service.TagsService;
import it.yuzuojian.com.service.TypeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagsService tagsService;
    @Autowired
    private ArticleTagsService articleTagsService;
    @GetMapping("/findAll")
    @RequiresPermissions("article_select")
    public String findAll(Model model,
                          @RequestParam(value = "page", defaultValue = "1") int page,
                          @RequestParam(value = "pageSize", defaultValue = "5") int pageSize){
        List<Article> articleList = articleService.findAll(page, pageSize);
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        model.addAttribute("types",typeService.findAll());
        model.addAttribute("pageInfo",pageInfo);
        return "admin/articles";

    }
    /*@PostMapping("/findAllPage")
    public String findAllPage(Model model,
                              SearchJavaBean data){
        List<Article> articleList = articleService.findAll(data.getPage(), 2);
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        System.out.println(pageInfo);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/articles :: articleList";

    }*/
    @RequiresPermissions("article_select")
    @PostMapping("/searchArticle")
    public String searchArticle(Model model,
                                @RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                SearchJavaBean data,Boolean isSearch){


        if("".equals(data.getTitle())){
            data.setTitle(null);
        }
        if("".equals(data.getTypeName())){
            data.setTypeName(null);
        }
        List<Article> articleList = articleService.searchArticle(page, pageSize,data.getTypeName(),data.getTitle(),data.getRecommend());
        PageInfo<Article> pageInfo=new PageInfo<>(articleList);
        model.addAttribute("pageInfo",pageInfo);
        if(isSearch){
            model.addAttribute("msg","搜素成功！");
        }
        return "admin/articles :: articleList";

    }
    @Transactional
    @GetMapping("/{id}/delete")
    @RequiresPermissions("article_del")
    public String delete(RedirectAttributes attributes, @PathVariable("id") Integer id) {
        try {
            articleService.deleteById(id);
            articleTagsService.deleteByArticleId(id);
            attributes.addFlashAttribute("msg", "删除完成");
        } catch (Exception e) {
            attributes.addFlashAttribute("msg", "删除失败");
            return "redirect:/admin/tags/findAll";
        }
        return "redirect:/admin/article/findAll";
    }

    @GetMapping("/add/index")
    @RequiresPermissions("article_add")
    public String addIndex(Model model) {
        model.addAttribute("article", new Article());
        model.addAttribute("types",typeService.findAll());
        model.addAttribute("tags",tagsService.findAll());
        return "admin/article-input";
    }

    @Transactional
    @PostMapping("/add")
    @RequiresPermissions("article_add")
    public String add(Article article, Model model, RedirectAttributes attributes,String tagIds) {
        article.setCreateTime(new Date());
        Integer articleId = articleService.findNextId();
        article.setLikeCount(0);
        article.setId(articleId);
        article.setViewCount(0);
        if(article.getCommentEable1()==null){
            article.setCommentEable1(false);
        }

        //处理articleTags表
        ArticleTags articleTags=new ArticleTags();
        articleTags.setArticleId(articleId);
        String[] articleTags_tagIds= tagIds.split(",");
        try {
            articleService.add(article);
            typeService.addCount(article.getTypeName());
            for (String articleTags_tagId : articleTags_tagIds) {
                articleTags.setTagId(Integer.parseInt(articleTags_tagId));
                articleTagsService.add(articleTags);
                tagsService.addCount(articleTags.getTagId());
            }
            attributes.addFlashAttribute("msg", "添加完成");
        } catch (Exception e) {
            e.printStackTrace();
            attributes.addFlashAttribute("msg", "添加失败");
        }
        return "redirect:/admin/article/findAll";
    }
    @GetMapping("/update/index")
    @RequiresPermissions("article_update")
    public String updateIndex(Model model,Integer id) {
        Article article = articleService.findById(id);
        String tagIds="";
        List<Integer> list=new ArrayList<>();
        for (Tags tags : article.getTagsList()) {
            list.add(tags.getId());
        }
        for (int i = 0; i < list.size(); i++) {
            if(i==(list.size()-1)){
                tagIds=tagIds+list.get(i);
            }else {
                tagIds=tagIds+list.get(i)+",";
            }
        }
        model.addAttribute("article",article);
        model.addAttribute("types",typeService.findAll());
        model.addAttribute("tags",tagsService.findAll());
        model.addAttribute("tagIds",tagIds);
        System.out.println(article);
        return "admin/article-input";
    }
    @PostMapping("/{id}/update")
    @RequiresPermissions("article_update")
    public String update(@PathVariable(value = "id") Integer id,Article article,
                         RedirectAttributes attributes,String tagIds,String beforeTypeName,String beforeTagIds){
        article.setUpdateTime(new Date());
        ArticleTags articleTags=new ArticleTags();
        articleTags.setArticleId(id);
        String[] articleTags_tagIds= tagIds.split(",");
        String[] beforeTagIdsArray= beforeTagIds.split(",");
        if(article.getCommentEable1()==null){
            article.setCommentEable1(false);
        }
        try {
            articleService.update(article);
            typeService.deleteCount(beforeTypeName);
            typeService.addCount(article.getTypeName());
            articleTagsService.deleteByArticleId(id);
            if(!beforeTagIds.equals("")){
                for (String beforeTagId : beforeTagIdsArray) {
                    tagsService.deleteCount(Integer.parseInt(beforeTagId));
                }
            }
            if(!tagIds.equals("")){
                for (String articleTags_tagId : articleTags_tagIds) {
                    articleTags.setTagId(Integer.parseInt(articleTags_tagId));
                    articleTagsService.add(articleTags);
                    tagsService.addCount(articleTags.getTagId());

                }
            }


            attributes.addFlashAttribute("msg", "修改完成");

        }catch (Exception e){
            e.printStackTrace();
            attributes.addFlashAttribute("msg", "修改失败");
        }



        return "redirect:/admin/article/findAll";
    }



}
